package com.zhuyuan.auth.service.impl;

import com.zhuyuan.core.constant.Oauth2Constants;
import com.zhuyuan.core.enums.CommonEnum;
import com.zhuyuan.core.util.Result;
import com.zhuyuan.redis.RedisService;
import com.zhuyuan.security.service.BaseUserDetailsService;
import com.zhuyuan.security.service.UserDetailsImpl;
import com.zhuyuan.system.api.domain.UserInfo;
import com.zhuyuan.system.api.feign.ISysUserApi;
import feign.RetryableException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @Author: 张琳凯
 * @Description: UserDetailService实现类
 * 用户数据表SysUser->UserInfo->UserDetailsImpl(User实现类)
 * @DateTime: 2025/1/6 20:43
 **/
@Service
@Slf4j
public class UserDetailServiceImpl implements BaseUserDetailsService {
//    String xxx = "{\n" +
//            "\t\"permissionList\": [\"student\", \"teacher\"],\n" +
//            "\t\"user\": {\n" +
//            "\t\t\"userId\": \"1\",\n" +
//            "\t\t\"userName\": \"ebbing-web\",\n" +
//            "\t\t\"password\": \"$2a$10$1ADAWlYscr2Ukcekcn.MQuT11OZaXc/Yl4vosziz1lZjL4YYARSMq\"\n" +
//            "\t}\n" +
//            "}";
    @Resource
    private ISysUserApi userApi;
    @Resource
    private RedisService redisService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        //todo 查询数据库的账户和密码，与传入的进行匹配，对应的参数是：username  password
        Result<UserInfo> userInfo =null;
        try {
            userInfo = userApi.infoByUserNameOrPhone(username,"");
        }catch (RetryableException e){
            log.error("调用用户服务超时");
        }
        return userInfoToUserDetails(userInfo);
    }

    @Override
    public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
        Result<UserInfo> userInfo =null;
        try {
            userInfo = userApi.infoByUserNameOrPhone("", mobile);
        }catch (RetryableException e){
            log.error("调用用户服务超时");
        }
        return userInfoToUserDetails(userInfo);
    }

    @Override
    public UserDetails loadUserBySocial(String openId) throws UsernameNotFoundException {
        Result<UserInfo> userInfo =null;//= JSON.parseObject(xxx, UserInfo.class);//userService.getUserByUsername(username);
        return userInfoToUserDetails(userInfo);
    }

    private UserDetails userInfoToUserDetails(Result<UserInfo> userInfoResult){
        if (userInfoResult==null||userInfoResult.getData()==null){
            throw new IllegalArgumentException("该用户信息不存在");
        }

        UserInfo userInfo=userInfoResult.getData();

        //将用户信息存储到redis中，减少token的长度
        //key:TAG+UID
        String authKey = Oauth2Constants.REDIS_USER_AUTHORITIES_CODE + userInfo.getUser().getUserId();
        redisService.setCacheObject(authKey,userInfo);

//        Collection<? extends GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(Convert.toStrArray(userInfo.getPermissionList()));
        return new UserDetailsImpl(
                userInfo.getUser().getUserId(),
                userInfo,
                userInfo.getUser().getUserName(),
                userInfo.getUser().getPassword(),
                CommonEnum.ENABLE.code == (userInfo.getUser().getStatus()==null?0:userInfo.getUser().getStatus()),
                true,
                true,
                true,
                new ArrayList<>());
    }
}
